<template>
    <img :src="imgUrl" :class="{'is-error':isError}" alt="">
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from 'vue'
const props = defineProps<{
    file: any
}>()
const imgUrl = ref<string | undefined>(undefined)
const isError = ref(false)
// watchEffect
onMounted(() => {

    let file = props.file
    if(file == null){
        isError.value = true
        imgUrl.value = '/state/null.png'
        return
    }
    if (!file.type || !file.type.includes('image/')) {
        isError.value = true
        imgUrl.value = '/state/file.png'
        // 不是图片
        return
    }
    const img = new Image()
    img.src = window.URL.createObjectURL(file)
    img.onload = () => {
        const { width, height } = img
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        canvas.width = width
        canvas.height = height
        canvas.style.cssText = `position: fixed; left: 0; top: 0; width: ${width}px; height: ${height}px; z-index: 9999; display: none;`
        document.body.appendChild(canvas)
        ctx === null || ctx === void 0
            ? void 0
            : ctx.drawImage(img, 0, 0, width, height)
        const dataURL = canvas.toDataURL()
        document.body.removeChild(canvas)
        imgUrl.value = dataURL
    }
})
</script>

<style scoped lang="scss">
.is-error{
    width: 30px !important;
    height: 30px !important;
    padding: 15px !important;
}
</style>